<template>
  <div class="role-management-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h2 class="page-title">
          <el-icon class="title-icon">
            <Setting />
          </el-icon>
          角色管理
        </h2>
        <p class="page-description">管理系统中的所有角色和权限分配</p>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="showCreateDialog" class="add-role-btn">
          <el-icon>
            <Plus />
          </el-icon>
          创建角色
        </el-button>
      </div>
    </div>

    <!-- 表格容器 -->
    <div class="table-container">
      <el-table :data="roles" v-loading="loading" style="width: 100%" border
        :header-cell-style="{ background: '#f8f9fa', color: '#495057', fontWeight: '600' }"
        :cell-style="{ padding: '16px 12px' }" class="role-table" table-layout="auto"
        element-loading-text="加载中..." element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(255, 255, 255, 0.8)">
        <el-table-column prop="name" label="角色名称" width="200"/>
        <el-table-column prop="description" label="描述" width="250"/>
        <el-table-column prop="createTime" label="创建时间" width="250">
          <template #default="{ row }">
            <span>{{ formatDateTime(row.createTime || row.create_time) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="250">
          <template #default="{ row }">
            <span>{{ formatDateTime(row.updateTime || row.update_time) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="permissionCount" label="权限数量" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getPermissionCountTagType(row.permissionCount || row.permission_count || 0)" size="small">
              {{ row.permissionCount || row.permission_count || 0 }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280">
          <template #default="scope">
            <div class="action-buttons">
              <el-button size="small" @click="showEditDialog(scope.row)">
                编辑
              </el-button>
              <el-button size="small" type="danger" @click="deleteRole(scope.row.roleId)">
                删除
              </el-button>
              <el-button size="small" type="warning" @click="showPermissionDialog(scope.row)">
                分配权限
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 创建/编辑角色对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
      <el-form :model="roleForm" :rules="formRules" ref="roleFormRef" label-width="100px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="roleForm.description" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveRole" :loading="saving">
          {{ saving ? '保存中...' : '保存' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog v-model="permissionDialogVisible" title="分配权限" width="600px">
      <el-transfer
        v-model="selectedPermissions"
        :data="allPermissions"
        :titles="['可选权限', '已选权限']"
        :props="{
          key: 'code',
          label: 'name'
        }"
      />
      <template #footer>
        <el-button @click="permissionDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="assignPermissions" :loading="assigning">
          {{ assigning ? '分配中...' : '分配权限' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Setting, Plus } from '@element-plus/icons-vue'
import { roleApi, permissionApi } from '@/api'

// 响应式数据
const roles = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const permissionDialogVisible = ref(false)
const isEdit = ref(false)
const saving = ref(false)
const assigning = ref(false)
const selectedRole = ref(null)
const allPermissions = ref([])
const selectedPermissions = ref([])

const roleForm = reactive({
  name: '',
  description: ''
})

const formRules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 50, message: '角色名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '描述不能超过200个字符', trigger: 'blur' }
  ]
}

const roleFormRef = ref()

// 工具函数
const formatDateTime = (dateTime) => {
  if (!dateTime) return '未设置'
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

const getPermissionCountTagType = (count) => {
  if (count === 0) return 'info'
  if (count <= 5) return 'success'
  if (count <= 10) return 'warning'
  return 'danger'
}

// 计算属性
const dialogTitle = computed(() => isEdit.value ? '编辑角色' : '创建角色')

// 获取角色列表
const getRoles = async () => {
  loading.value = true
  try {
    const response = await roleApi.getRoles()
    roles.value = response.data || []
    console.log('角色数据:', roles.value)
  } catch (error) {
    ElMessage.error('获取角色列表失败：' + (error.response?.data?.message || error.message))
  } finally {
    loading.value = false
  }
}

// 获取权限列表
const getPermissions = async () => {
  try {
    const response = await permissionApi.getPermissions()
    allPermissions.value = response.data || []
  } catch (error) {
    ElMessage.error('获取权限列表失败：' + (error.response?.data?.message || error.message))
  }
}

// 显示创建对话框
const showCreateDialog = () => {
  isEdit.value = false
  roleForm.name = ''
  roleForm.description = ''
  dialogVisible.value = true
}

// 显示编辑对话框
const showEditDialog = (role) => {
  isEdit.value = true
  selectedRole.value = role
  roleForm.name = role.name
  roleForm.description = role.description
  dialogVisible.value = true
}

// 保存角色
const saveRole = async () => {
  if (!roleFormRef.value) return
  
  try {
    const valid = await roleFormRef.value.validate()
    if (valid) {
      saving.value = true
      
      if (isEdit.value) {
        // 更新角色
        await roleApi.updateRole(selectedRole.value.roleId, roleForm)
        ElMessage.success('角色更新成功')
      } else {
        // 创建角色
        await roleApi.createRole(roleForm)
        ElMessage.success('角色创建成功')
      }
      
      dialogVisible.value = false
      getRoles()
    }
  } catch (error) {
    ElMessage.error('操作失败：' + (error.response?.data?.message || error.message))
  } finally {
    saving.value = false
  }
}

// 删除角色
const deleteRole = async (roleId) => {
  try {
    await ElMessageBox.confirm('确定要删除这个角色吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await roleApi.deleteRole(roleId)
    ElMessage.success('角色删除成功')
    getRoles()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败：' + (error.response?.data?.message || error.message))
    }
  }
}

// 显示权限分配对话框
const showPermissionDialog = async (role) => {
  selectedRole.value = role
  selectedPermissions.value = []
  permissionDialogVisible.value = true
  
  // 获取角色当前权限
  try {
    const response = await roleApi.getRolePermissions(role.roleId)
    if (response.data) {
      selectedPermissions.value = response.data.map(permission => permission.code || permission.id)
    }
  } catch (error) {
    console.error('获取角色权限失败:', error)
  }
}

// 分配权限
const assignPermissions = async () => {
  try {
    assigning.value = true
    // 过滤掉null和undefined值，只发送有效的权限编码
    const validPermissions = selectedPermissions.value.filter(code => code != null && code !== '')
    await roleApi.assignPermissionsToRole(selectedRole.value.roleId, validPermissions)
    ElMessage.success('权限分配成功')
    permissionDialogVisible.value = false
  } catch (error) {
    ElMessage.error('权限分配失败：' + (error.response?.data?.message || error.message))
  } finally {
    assigning.value = false
  }
}

// 页面加载时获取数据
onMounted(() => {
  getRoles()
  getPermissions()
})
</script>

<style scoped>
.role-management-container {
  width: 100%;
  min-height: calc(100vh - 60px);
  display: flex;
  flex-direction: column;
  padding: 20px;
  box-sizing: border-box;
  background: #f5f7fa;
  margin: 0;
  overflow-y: auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  flex-shrink: 0;
}

.header-left {
  flex: 1;
  margin-right: 20px;
}

.header-right {
  flex-shrink: 0;
}

.page-title {
  display: flex;
  align-items: center;
  font-size: 1.8rem;
  color: #303133;
  margin: 0 0 5px 0;
}

.title-icon {
  margin-right: 8px;
  font-size: 1.8rem;
  color: #409eff;
}

.page-description {
  font-size: 0.9rem;
  color: #606266;
  margin: 0;
}

.add-role-btn {
  height: 40px;
  padding: 0 20px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 8px;
}

.table-container {
  flex: 1;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  margin: 0;
  padding: 16px 20px;
  min-height: 300px;
}

.role-table {
  width: 100%;
  flex: 1;
}

.role-table :deep(.el-table__header-wrapper) {
  background: #f5f7fa;
}

.role-table :deep(.el-table__body-wrapper) {
  overflow: auto;
  min-height: 300px;
}

.role-table :deep(.el-table__row) {
  transition: background-color 0.3s ease;
}

.role-table :deep(.el-table__row:hover) {
  background-color: #f5f7fa;
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
  align-items: center;
}

.action-buttons .el-button {
  margin: 0;
  flex-shrink: 0;
}

/* 确保表格完整显示 */
.role-table :deep(.el-table) {
  width: 100% !important;
  height: auto !important;
  display: table !important;
  table-layout: auto !important;
}

.role-table :deep(.el-table__body) {
  width: 100% !important;
  height: auto !important;
}

.role-table :deep(.el-table__header) {
  width: 100% !important;
  height: auto !important;
}

/* 确保表格列宽度正确 */
.role-table :deep(.el-table__column) {
  min-width: 0;
}

/* 确保表格内容不被截断 */
.role-table :deep(.el-table__cell) {
  padding: 12px 8px !important;
  word-break: break-word;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  box-sizing: border-box;
}

/* 确保操作按钮正确显示 */
.role-table :deep(.el-button) {
  margin: 2px;
  min-width: 60px;
}

/* 确保标签正确显示 */
.role-table :deep(.el-tag) {
  margin: 0;
  display: inline-block;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .role-management-container {
    padding: 15px;
  }

  .page-header {
    margin-bottom: 15px;
    padding: 15px;
  }

  .table-container {
    padding: 15px;
  }

  .role-table :deep(.el-table__cell) {
    padding: 8px 6px !important;
  }
}

@media (max-width: 768px) {
  .role-management-container {
    padding: 10px;
  }

  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
    margin-bottom: 10px;
    padding: 15px;
  }

  .add-role-btn {
    width: 100%;
  }

  .table-container {
    padding: 10px;
  }

  .role-table :deep(.el-table__cell) {
    padding: 4px 2px !important;
  }
}

@media (max-width: 480px) {
  .role-management-container {
    padding: 8px;
  }

  .page-header {
    padding: 12px;
  }

  .table-container {
    padding: 8px;
  }

  .role-table :deep(.el-table__cell) {
    padding: 2px 1px !important;
    font-size: 11px;
  }
}

.el-transfer {
  width: 100%;
  display: flex;
  justify-content: space-between;
}
</style>